import axios from "axios";
import { useRouter } from "vue-router";
import nProgress from "nprogress";
import 'nProgress/nprogress.css'
import { showDialog } from 'vant';

let http = axios.create({
    baseURL: "http://192.168.15.224:8888",
    headers: {
        "Content-Type": "application/json" // 默认使用 JSON
    }
});

// 动态设置 Content-Type
http.interceptors.request.use(config => {
    if (config.data instanceof FormData) {
        config.headers['Content-Type'] = 'multipart/form-data';
    } else if (typeof config.data === 'string') {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    }
    nProgress.start();
    return config;
}, error => {
    return Promise.reject(error);
});

// 添加响应拦截器
http.interceptors.response.use(function (response) {
    nProgress.done()
    console.log(response.data);
    if (response.data && response.data.code === 401) {
        showDialog({
            message: "token过期,请重新登录",
            theme: 'round-button',
        }).then(() => {
            localStorage.removeItem("token");
            let router = useRouter();
            router.push("/login");
            // on close
        });
        console.log("token过期");
    }
    return response;
}, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么   
    nProgress.done()
    return Promise.reject(error);
});

export default http;